﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Compilation;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Specialized;
using System.Web;

namespace WorkflowManagement.Web.UI
{
    /// <summary>
    /// A base class for condition that when triggered execute the specified workflow.
    /// </summary>
    public abstract class WorkflowTrigger
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="WorkflowTrigger"/> class.
        /// </summary>
        protected WorkflowTrigger()
        {
        }
        
        private WorkflowManagerBase _manager;

        /// <summary>
        /// Gets the active <see cref="WorkflowManagerBase">manager</see>.
        /// </summary>
        /// <value>The active manager.</value>
        protected WorkflowManagerBase Manager
        {
            get { return _manager; }
        }

        private string _workflowType;

        /// <summary>
        /// Gets or sets the type of the workflow.
        /// </summary>
        /// <value>The type of the workflow.</value>
        public string WorkflowType
        {
            get { return _workflowType; }
            set { _workflowType = value; }
        }

        private ParameterCollection _parameters = new ParameterCollection();

        /// <summary>
        /// A collection of parameters used to transfer data to and from the <see cref="WorkflowManager"/>.
        /// </summary>
        [PersistenceMode(PersistenceMode.InnerProperty)]
        public ParameterCollection Parameters
        {
            get { return _parameters; }
        }

        /// <summary>
        /// Initializes the specified manager.
        /// </summary>
        /// <param name="manager">The manager.</param>
        internal void Initialize(WorkflowManagerBase manager)
        {
            this._manager = manager;
            Initialize();
        }

        /// <summary>
        /// Initializes this trigger.
        /// </summary>
        protected abstract void Initialize();

        /// <summary>
        /// Called when the condition is triggered.
        /// </summary>
        protected void OnTrigger()
        {   
            _manager.ExecuteWorkflow(BuildManager.GetType(_workflowType, true), GetParameters());
        }

        private Dictionary<string, object> GetParameters()
        {
            IOrderedDictionary values = _parameters.GetValues(HttpContext.Current, _manager);
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            foreach (string key in values.Keys)
                parameters.Add(key, values[key]);
            return parameters;
        }
    }
}
